// backend/src/mappers/sqlmapper/user/userMapper.js
import sequelize from "../../config/db.js";

class UserMapper {
    /**
     * 检查用户是否已存在
     * @param {Object} userData - 用户数据
     * @returns {Promise<Object|null>} - 返回现有用户的用户名或 null
     */
    static async existingUser(userData) {
        const [existingUser] = await sequelize.query(
            `
                SELECT username
                FROM sys_users
                WHERE username = :username
                  AND (isDeleted = 1 OR isDeleted = 0)
            `,
            {
                replacements: {username: userData.username}
            }
        );
        return existingUser;
    }

    /**
     * 创建新用户
     * @param {Object} userData - 用户数据
     * @param {string} hashedPassword - 哈希后的密码
     * @returns {Promise<void>}
     */
    static async createUser(userData, hashedPassword) {
        await sequelize.query(
            `INSERT INTO sys_users (username, email, password, name, sex, phone, address, role_id, status, bio,
                                    registeredIP)
             VALUES (:username, :email, :password, :name, :sex, :phone, :address, :role_id, :status, :bio,
                     :registeredIP)`,
            {
                replacements: {
                    username: userData.username,
                    email: userData.email || null,
                    password: hashedPassword,
                    name: userData.name || null,
                    sex: userData.sex || null,
                    phone: userData.phone || null,
                    address: userData.address || null,
                    role_id: userData.role_id || null,
                    status: userData.status || null,
                    bio: userData.bio || null,
                    registeredIP: userData.registeredIP
                }
            }
        );
    }

    /**
     * 获取指定用户名的用户信息
     * @param {string} username - 用户名
     * @param {number} userId
     * @returns {Promise<Object|null>} - 返回用户信息或 null
     */
    static async getUserName(username, userId) {
        // 初始化查询
        let query =
            `
                SELECT *
                FROM sys_users
                WHERE isDeleted = 1
            `;
        let replacements = {};

        // 根据条件动态添加 SQL 语句和 replacements
        if (username) {
            query += ` AND username = :username`;
            replacements.username = username;
        }

        if (userId) {
            query += ` AND user_id = :userId`;
            replacements.userId = userId;
        }

        // 执行查询
        const [user] = await sequelize.query(query, {
            replacements
        });

        return user;
    }


    /**
     * 更新用户最后登录信息
     * @param {Array} user - 用户数据数组
     * @param {string} ipAddress - 登录 IP 地址
     * @returns {Promise<void>}
     */
    static async loginUser(user, ipAddress) {
        await sequelize.query(
            `UPDATE sys_users
             SET lastLoginAt = :lastLoginAt,
                 lastLoginIP = :lastLoginIP
             WHERE user_id = :user_id`,
            {
                replacements: {
                    lastLoginAt: new Date(),
                    lastLoginIP: ipAddress,
                    user_id: user[0].user_id
                }
            }
        );
    }

    /**
     * 更新用户信息
     * @param fields
     * @param {Object} userData - 用户数据
     * @param {number} userId - 用户 ID
     * @returns {Promise<void>}
     */
    static async updateUser(fields, userData, userId) {
        await sequelize.query(
            `UPDATE sys_users
             SET ${fields}
             WHERE user_id = :userId
               AND isDeleted = 1`,
            {
                replacements: {...userData, userId} // 这里确保 userData 和 userId 一起传递
            }
        );
    }

    /**
     * 逻辑删除用户
     * @param {Array<number>} userIds - 要删除的用户 ID 数组
     * @returns {Promise<void>}
     */
    static async deleteUser(userIds) {
        await sequelize.query(
            `UPDATE sys_users
             SET isDeleted = 0
             WHERE user_id IN (:userIds)`,
            {
                replacements: {userIds}
            }
        );
    }

    /**
     * 获取所有用户的信息
     * @returns {Promise<Array>} - 返回用户信息数组
     */
    static async getAllUsers() {
        return await sequelize.query(
            `
                SELECT *
                from sys_users
                where isDeleted = 1
            `
        );
    }
}

export default UserMapper;
